package site.jlopen.controller.api;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import site.jlopen.assets.config.ThreadAuthUser;
import site.jlopen.domain.data.KusciaData;
import site.jlopen.domain.data.KusciaDataColumn;
import site.jlopen.domain.data.event.KusciaDataEvent;
import site.jlopen.domain.datasource.KusciaDatasource;
import site.jlopen.domain.datasource.event.KusciaDatasourceEvent;
import site.jlopen.domain.node.event.KusciaNodeEvent;
import site.jlopen.entity.BaseResponse;
import site.jlopen.kuscia.service.data.AbstractDataManager;
import site.jlopen.mapper.data.KusciaDataColumnMapper;
import site.jlopen.mapper.data.KusciaDataMapper;
import site.jlopen.mapper.datasource.KusciaDatasourceMapper;
import site.jlopen.mapper.node.KusciaNodeMapper;
import site.jlopen.secret.model.data.SecretDataAllInfoResp;
import site.jlopen.secret.model.data.SecretDataCreateReq;
import site.jlopen.secret.model.data.SecretDataInfoResp;
import site.jlopen.secret.model.data.SecretDataTableStructure;
import site.jlopen.service.BaseService;
import site.jlopen.service.intf.data.DataService;
import site.jlopen.utils.id.IdUtils;

@RestController
@RequestMapping(value="/api/data")
public class ApiDataController extends BaseService {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private AbstractDataManager dataManager;
	@Autowired
	public DataService dataService;
	@Autowired
	private KusciaNodeMapper nodeMapper;
	@Autowired
	private KusciaDataMapper dataMapper;
	@Autowired
	private KusciaDataColumnMapper columnMapper;
	@Autowired
	private KusciaDatasourceMapper datasourceMapper;
	
	
	@PostMapping(value = "/create" )
	public BaseResponse<SecretDataInfoResp> create(@RequestBody SecretDataCreateReq form) {
		if(null == form.getStructures() || form.getStructures().size() == 0) {
			return new BaseResponse<SecretDataInfoResp>().error("未设置表结构");
		}
		KusciaNodeEvent node = nodeService.getNodeByCode(ThreadAuthUser.id(), form.getNodeCode());
		if(null == node) {
			return new BaseResponse<SecretDataInfoResp>().error("节点编号不存在");
		}
		KusciaDatasourceEvent datasource = datasourceMapper.selectByInfo(new KusciaDatasource().setDatasourceUserId(ThreadAuthUser.id()).setDatasourceCode(form.getDatasourceCode()));
		if(null == datasource) {
			return new BaseResponse<SecretDataInfoResp>().error("数据源不存在");
		}
		Long dataId = IdUtils.SnowFlakeId();
		List<KusciaDataColumn> cList = new ArrayList<KusciaDataColumn>();
		int cIndex = 1;
		for (SecretDataTableStructure structure : form.getStructures()) {
			cList.add(new KusciaDataColumn()
					.setColumnId(IdUtils.SnowFlakeId())
					.setColumnDataId(dataId)
					.setColumnSort(cIndex)
					.setColumnCreate(new Date())
					.setColumnName(structure.getColumnName())
					.setColumnType(structure.getColumnType().getCode())
					.setColumnDescription(structure.getColumnRemark()));
			cIndex ++;
		}
		columnMapper.insertBatch(cList);
		KusciaData dataEv = new KusciaData()
				.setDataId(dataId)
				.setDataNodeId(node.getNodeId())
				.setDataUserId(ThreadAuthUser.id())
				.setDataSourceId(datasource.getDatasourceId())
				.setDataDomaindataId(null)
				.setDataTitle(form.getTitle())
				.setDataNativeName(form.getFileName())
				.setDataRelativeName(form.getFileDir())
				.setDataType("table")
				.setDataDescription(form.getRemark())
				.setDataCreate(new Date())
				;
		int datar = dataMapper.insertSelective(dataEv);
		if(datar > 0) {
			BaseResponse<String> status = dataService.restatus(dataId);
			if(status.getStatus() != 0) {
				return new BaseResponse<SecretDataInfoResp>().error("数据已保存，但获取数据对象ID异常，请使用刷新接口重新获取：" + status.getMsg());
			}
			SecretDataInfoResp dinfo = new SecretDataInfoResp();
			dinfo.setDataId(dataId);
			dinfo.setDomainDataId(status.getData());
			return new BaseResponse<SecretDataInfoResp>().success("保存成功").setData(dinfo);
		}
		return new BaseResponse<SecretDataInfoResp>().error("保存失败");
	}
	
	@PostMapping(value = "/update" )
	public BaseResponse<String> update() {
		logger.info("数据接口调用");
		return new BaseResponse<String>().success("暂不支持");
	}
	
	@PostMapping(value = "/remove" )
	public BaseResponse<String> remove(Long dataId) {
		return new BaseResponse<String>().success("暂不支持");
	}
	
	@PostMapping(value = "/status" )
	public BaseResponse<String> status(Long dataId) {
		logger.info("数据接口调用");
		return dataService.restatus(dataId);
	}
	
	@PostMapping(value = "/info" )
	public BaseResponse<SecretDataInfoResp> info(Long dataId) {
		logger.info("数据接口调用");
		KusciaDataEvent dEvent = dataService.getData(dataId);
		if(null == dEvent) {
			return new BaseResponse<SecretDataInfoResp>().error("数据不存在");
		}
		SecretDataInfoResp dinfo = new SecretDataInfoResp();
		dinfo.setDataId(dataId);
		dinfo.setDomainDataId(dEvent.getDataDomaindataId());
		return new BaseResponse<SecretDataInfoResp>().success("保存成功").setData(dinfo);
	}
	
	@PostMapping(value = "/infoAll" )
	public BaseResponse<SecretDataAllInfoResp> infoAll(String nodeCode, String domainDataId) {
		logger.info("数据接口调用");
		return dataService.getDataByDomainDataId(ThreadAuthUser.id(), nodeCode, domainDataId);
	}
	
}